package com.longkier.gx_library_springboot.repository;

import com.longkier.gx_library_springboot.entity.Book;
import jakarta.validation.constraints.NotBlank;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

    // 首页获取指定数量不重复的最新图书详情，按更新时间排序，只查询状态为可借的书籍
    @Query("SELECT DISTINCT b FROM Book b " +
            "WHERE b.bookStatus = '可借' " +
            "ORDER BY b.updateTime DESC")
    List<Book> homeFindTopBooksByLatestUpdate(Pageable pageable);

    // 首页获取指定数量不重复的随机图书详情（使用原生SQL），只查询状态为可借的书籍
    @Query(value = "SELECT DISTINCT * FROM t_books " +
            "WHERE book_status = '可借' " +
            "ORDER BY RAND() LIMIT :limit", nativeQuery = true)
    List<Book> homeFindRandomBooks(int limit);

    boolean existsByBookNumber(String bookNumber);
    Book getBookNumberByBookId(Long bookId);

    @Modifying
    @Query("DELETE FROM Book b " +
            "WHERE b.bookId IN :bookId")
    int deleteAllByIdInBatch(@Param("bookId") List<Long> bookId);

    // 新增模糊查询方法
    @Query("SELECT b FROM Book b " +
            "WHERE (:bookNumber IS NULL OR b.bookNumber LIKE %:bookNumber%) " +
            "AND (:bookName IS NULL OR b.bookName LIKE %:bookName%) " +
            "AND (:bookAuthor IS NULL OR b.bookAuthor LIKE %:bookAuthor%) " +
            "AND (:bookArea IS NULL OR b.bookArea LIKE %:bookArea%) " +
            "AND (:bookType IS NULL OR b.bookType LIKE %:bookType%) " +
            "AND (:bookStatus IS NULL OR b.bookStatus = :bookStatus)")
    Page<Book> findByCriteria(@Param("bookNumber") String bookNumber,
                              @Param("bookName") String bookName,
                              @Param("bookAuthor") String bookAuthor,
                              @Param("bookArea") String bookArea,
                              @Param("bookType") String bookType,
                              @Param("bookStatus") String bookStatus,
                              Pageable pageable);


    List<Book> findByBookIdIn(List<Long> bookId);
    Optional<Book> findByBookNumber(@NotBlank(message = "图书编号不能为空") String bookNumber);
    boolean existsByBookType(String type);

    boolean existsByBookArea(String areaName);
}
